package cn.alone.org.controller;

import cn.alone.basic.util.AjaxResult;
import cn.alone.basic.util.PageList;
import cn.alone.org.domain.Department;
import cn.alone.org.query.DepartmentQuery;
import cn.alone.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 * 前后端交互接口层
 * @author lanan
 */
@Api
@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * //新增或修改
     * //RequestBody 将前端接收得对象解析位json格式
     * @param department
     * @return 链式编程
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.add(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败").setSuccess(false);
        }
    }

    //删除

    /**
     * /{id}直接接收前端传过来的参数
     * @PathVariable取值
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }

    }

    /**
     * 根据id查询一条数据
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult findById(@PathVariable("id") Long id){
        try {
            departmentService.loadById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 获取所有数据
     * @return
     */
    @GetMapping("/list")
    public List<Department> loadAll(){
        return departmentService.loadAll();
    }


    @PostMapping("/page")
    public PageList<Department> querPage(@RequestBody DepartmentQuery query){
        return departmentService.querpage(query);
    }

  /**
   * 批量删除
   * @param ids
   * @return
   */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
      try {
        departmentService.patchDelete(ids);
        return AjaxResult.me();
      } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("操作失败");
      }
    }

    /**
     * 返回部门一二级树形数据
     * @return
     */
    @PostMapping("/tree")
    public List<Department> findTree(){
        return departmentService.findTree();
    }
}
